package cn.gson.crm.controller.interview;

import cn.gson.crm.controller.BaseServlet;
import cn.gson.crm.model.Jdbc;
import cn.gson.crm.model.dao.AccessoryDao;
import cn.gson.crm.model.dao.InterviewDao;
import cn.gson.crm.model.entity.Interview;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;

/**
 * Servlet implementation class InterviewManagerServlet
 */
@WebServlet("/interview/manager")
public class InterviewManagerServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private InterviewDao dao = new InterviewDao();
	private AccessoryDao accessoryDao = new AccessoryDao();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void get(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String type = request.getParameter("type");
		String sql = "select * from province";
		if("city".equalsIgnoreCase(type)){
			String provinceId = request.getParameter("province");
			sql = "select * from city where province_id = " + provinceId;
		}else if("area".equalsIgnoreCase(type)){
			String cityId = request.getParameter("city");
			sql = "select * from area where city_id = " + cityId;
		}

		List<Map<String,Object>> map = Jdbc.getInstace().executeQueryForList(sql);
		if(type == null){
			request.setAttribute("provinceList", map);
			forward("interview/interview_manager.jsp");
		}else{
			String jsonStr = JSONArray.toJSONString(map);
			response.getWriter().append(jsonStr);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void post(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String[] attachs = request.getParameterValues("attachs");
		String companyName = request.getParameter("companyName");
		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String area = request.getParameter("area");
		String detailAddress = request.getParameter("detailAddress");
		String time = request.getParameter("time");
		String summary = request.getParameter("summary");
		String companyAddress = province + city + area + detailAddress;
		int stuId = 1;
		
		Interview view = new Interview();
		view.setCompanyName(companyName);
		view.setCompanyAddress(companyAddress);
		view.setInterviewSummary(summary);
		view.setInterviewTime(Date.valueOf(time));
		view.setStuId(stuId);
		
		Long id = dao.saveInterview(view);
		if(id != null){
			if(attachs != null && attachs.length > 0){
				accessoryDao.guanLian(id, attachs);
			}
	 		redirect("interview/form");
	 	}else{
	 		redirect("interview/interview_manager.jsp");
	 	}
	}

}
